package com.carful.xigua.modules.common.util;


import com.carful.xigua.modules.common.config.SecurityConfig;
import com.carful.xigua.modules.common.config.XiguaConfig;
import com.carful.xigua.modules.user.entity.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author ad
 * Date 2024/1/22 下午7:47
 * Description
 */

@Component
public class SecurityContextUtils {

    public static Authentication getAuthentication() {
        XiguaConfig properties = SpringContextUtil.getContext().getBean(XiguaConfig.class);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (null == authentication && "dev".equals(properties.getActive())) {
            User user = new User().setUsername("dev").setUsername("开发账号").setOrgId(1);
            return new UsernamePasswordAuthenticationToken(new SecurityConfig.LoginUserDetails(user, user.getAuthorities()), null, new ArrayList<>());
        }
        if (authentication instanceof UsernamePasswordAuthenticationToken) return authentication;
        else throw new UsernameNotFoundException("认证错误");
    }

    public static SecurityConfig.LoginUserDetails getLoginUserDetails() {
        SecurityConfig.LoginUserDetails userDetails = (SecurityConfig.LoginUserDetails) getAuthentication().getPrincipal();
        return userDetails;
    }

    public static String getUsername() {
        String username = getLoginUserDetails().getUsername();
        return username;
    }

}
